package com.qf.blog.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 拦截器：在调用Controller之前被执行
// 这个拦截器不需要在Controller之前干活，需要在之后干活(负责把用户的登录信息从session挪到Model)
@Component // 自定义拦截器放入到IOC容器中
public class LoginUserInterceptor implements HandlerInterceptor {

    // 在Controller之前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true; // 直接放行
    }

    // 在Controller之后调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(modelAndView != null){
            // 1、先从session作用域取出来
            Object user = request.getSession().getAttribute("loginUser");
            if (user != null) {
                // 已经登陆了，才把用户信息给保存到Model中
                modelAndView.addObject("loginUser",user);
            }
        }
    }

    // 在视图渲染完成之后调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
